#include "GLPicker.h"

namespace coolpool
{

	GLPicker::GLPicker()
	{

	}

	GLPicker::~GLPicker()
	{

	}

	void GLPicker::processHits(GLint hits, GLuint buffer[])
	{
		GLuint names, *ptr, minZ, *ptrNames, numberOfNames;

		std::cout << "hits = " << hits << std::endl;
		ptr = (GLuint *) buffer;
		minZ = 0xffffffff;
		for (int i = 0; i < hits; i++)
		{
			names = *ptr;
			ptr++;
			if (*ptr < minZ)
			{
				numberOfNames = names;
				minZ = *ptr;
				ptrNames = ptr + 2;
			}

			ptr += names + 2;
		}
		std::cout << "The closest hit names are ";
		ptr = ptrNames;
		for (unsigned j = 0; j < numberOfNames; j++, ptr++)
		{
			std::cout << *ptr;
		}
		std::cout << std::endl;
	}

	void GLPicker::stopPicking()
	{

		int hits;

		// restoring the original projection matrix
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glFlush();

		// returning to normal rendering mode
		hits = glRenderMode(GL_RENDER);

		// if there are hits process them
		if (hits != 0)
			processHits(hits, selectBuf);
	}

	void GLPicker::startPicking(int cursorX, int cursorY)
	{

		GLint viewport[4];

		glSelectBuffer(BUFF_SIZE, selectBuf);
		glRenderMode(GL_SELECT);

		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();

		glGetIntegerv(GL_VIEWPORT, viewport);
		gluPickMatrix(cursorX, viewport[3] - cursorY, 5, 5, viewport);
		gluPerspective(60.0f, (GLfloat) glutGet(GLUT_WINDOW_WIDTH) / (GLfloat) glutGet(GLUT_WINDOW_HEIGHT), 1.0f, 2000.0f);
		glMatrixMode(GL_MODELVIEW);
		glInitNames();
	}
}
